package cn.lyl.pet.service.impl;

import cn.lyl.basic.exception.BusinessException;
import cn.lyl.basic.service.IBaiduAiAuditService;
import cn.lyl.basic.util.*;
import cn.lyl.order.domain.OrderPetAcquisition;
import cn.lyl.order.mapper.OrderPetAcquisitionMapper;
import cn.lyl.org.domain.Employee;
import cn.lyl.org.domain.Shop;
import cn.lyl.org.mapper.EmployeeMapper;
import cn.lyl.org.mapper.ShopMapper;
import cn.lyl.pet.domain.SearchMasterMsg;
import cn.lyl.pet.domain.SearchMasterMsgAuditLog;
import cn.lyl.pet.dto.MsgDto;
import cn.lyl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.lyl.pet.mapper.SearchMasterMsgMapper;
import cn.lyl.pet.query.SearchMasterMsgQuery;
import cn.lyl.pet.service.ISearchMasterMsgService;
import cn.lyl.basic.service.impl.BaseServiceImpl;
import cn.lyl.user.domain.Logininfo;
import cn.lyl.user.domain.User;
import cn.lyl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //1.添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLoginoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.add(msg);//自增Id
        //2.百度AI智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        if(boo1 && boo2){//审核通过
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.add(log);
            //获取离4用户最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.findAll());
            if(nearestShop!=null){//找到最近的店铺
                msg.setShopId(nearestShop.getId());
                //发消息-店铺
                //SmsUtils.sendSms(nearestShop.getTel(),"您有新的订单，请尽快去"+msg.getAddress()+"处理");
                System.out.println("您有新的订单，请尽快去"+msg.getAddress()+"处理");
            }else {//50公里内没有找到最近的店铺
                //放入寻主池
                msg.setState(3);
                //发消息-用户
                //SmsUtils.sendSms(user.getPhone(),"抱歉！您周边暂时还没店铺入驻，请耐心等待！！");
                System.out.println("抱歉！您周边暂时还没店铺入驻，请耐心等待！！");
            }
            searchMasterMsgMapper.update(msg);
            return new AjaxResult();//return 前端
        }else {//审核不通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            //发消息-用户
            //SmsUtils.sendSms(user.getPhone(),"抱歉！您周边暂时还没店铺入驻，请耐心等待！！");
            System.out.println("寻主消息发布失败，请修改之后重新发布！");
            //删除寻主信息
            searchMasterMsgMapper.del(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("发布失败！");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息 设置User_id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLoginoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询已完成的寻主
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLoginfoId(logininfo.getId());
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询寻主池的消息
        query.setState(3);

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLoginfoId(logininfo.getId());
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        //拒单：寻主消息已经分配给某一个店铺，店铺拒单了
        //拒单之后，放入寻主池 - state=3，置空店铺id
        searchMasterMsgMapper.reject(id);

    }

    @Override
    public void accept(MsgDto msgDto) {
        //判断订单是否存在，如果有人处理就不应该重复处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.findByMsgId(msgDto.getMsgId());
        if(order!=null && order.getState()==0){
            throw new BusinessException("该订单正在处理中，请勿重复操作！");
        }
        //1.生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(msgDto.getMsgId());
        OrderPetAcquisition newOder = creatOder(msg,msgDto);
        orderPetAcquisitionMapper.add(newOder);
        //2.告诉处理人在规定的时间内去接宠物：发短信 2day
        //Employee employee = employeeMapper.findOne(msgDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"您有新的订单，请在两天内去"+msg.getAddress()+"处理");
        System.out.println("您有新的订单，请在两天内去"+msg.getAddress()+"处理");
    }

    private OrderPetAcquisition creatOder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        //最后确认时间 -  2天后的此刻
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setState(0);
        //order.setPrice(msg.getPrice());-没有 接宠物的时候才有
        //order.setPaytype(0); - 实体类默认待处理0
        //order.setPetId(); - 没有接宠物来后才有
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }


}
